package management;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class UDPManager {
	private static UDPManager instance;
	
	private int port = 3000;
	private DatagramSocket socket;
	private InetAddress inetAddress;

	public static UDPManager getUDPManager()
	{
		if (instance == null)
		{
			try{
				instance = new UDPManager();
			}
			catch (Exception e)
			{
				instance = null;
			}
		}
		
		return instance;
	}
	
	private UDPManager() throws UnknownHostException, SocketException
	{
		inetAddress = InetAddress.getLocalHost();
		
		socket = new DatagramSocket();
		
		setTimeout(1);
		
		if (!(send("WebcamApp Opening")))
			throw new SocketException("Could not send through the opened socket.");
	}
	
	public boolean send(String data)
	{
		byte[] sendData = data.getBytes();
		DatagramPacket packet = new DatagramPacket(sendData, sendData.length, inetAddress, port);
		try {
			socket.send(packet);
			return true;
		} catch (IOException e) {
			return false;
		}
	}
	
	public String receive()
	{
		byte[] recBuffer = new byte[1024];
		
		DatagramPacket recPacket = new DatagramPacket(recBuffer, recBuffer.length);
		
		try {
			socket.receive(recPacket);
		}
		catch (Exception e)
		{
		}
		
		byte[] receivedData = new byte[recPacket.getLength()];
		
		for (int i = 0; i < recPacket.getLength() && i < recBuffer.length; i++)
		{
			receivedData[i] = recBuffer[i];
		}
		
		return new String(receivedData);
	}
	
	public void setTimeout(int milliseconds)
	{
		try {
			socket.setSoTimeout(milliseconds);
		} catch (SocketException e) {
		}
	}
}
